// 测试用例管理页面JavaScript - 引导式创建
document.addEventListener('DOMContentLoaded', function() {
    // 检查当前页面是哪个，以决定执行哪种初始化
    const currentPath = window.location.pathname;
    
    if (currentPath === '/test-cases' || currentPath === '/test-cases/') {
        // 为测试用例表格绑定动态事件（事件委托）
        const tableBody = document.querySelector('#testCasesTable tbody');
        if (tableBody) {
            bindDynamicButtonEvents(tableBody);
        }
        
        // 加载测试用例列表页面
        loadTestCases();
        updateTestCaseStats();
        
        // 初始化向导（用于模态框）
        initializeModalWizard();
        
        // 读写类型选择变化事件
        const rwTypeSelect = document.getElementById('rwType');
        if (rwTypeSelect) {
            rwTypeSelect.addEventListener('change', handleRwTypeChange);
            // 初始化时处理默认值
            handleRwTypeChange();
        }
        
        // 编辑模态框中的读写类型选择变化事件
        const editRwTypeSelect = document.getElementById('editRwType');
        if (editRwTypeSelect) {
            editRwTypeSelect.addEventListener('change', handleEditRwTypeChange);
        }
        
        // 保存编辑按钮事件
        const saveEditBtn = document.getElementById('saveEditTestCaseBtn');
        if (saveEditBtn) {
            saveEditBtn.addEventListener('click', saveEditedTestCase);
        }
    } else if (currentPath === '/test-cases/create') {
        // 初始化创建页面的向导
        initializeCreateWizard();
    }
});

// 初始化向导（通用函数）
function initializeWizard(isModal = false) {
    // 对于单页面表单，不需要步骤导航
    
    // 注意：模态框中的按钮需要在模态框显示时绑定事件
}

// 初始化模态框向导（使用通用函数）
function initializeModalWizard() {
    initializeWizard(true);
    
    // 为模态框按钮绑定事件（在模态框显示时才绑定）
    const modal = document.getElementById('addTestCaseModal');
    if (modal) {
        modal.addEventListener('shown.bs.modal', function () {
            // 模态框显示后绑定按钮事件
            const saveBtn = document.getElementById('saveTestCaseBtn');
            if (saveBtn) {
                saveBtn.addEventListener('click', saveTestCase);
            }
            
            // 重新绑定其他需要的事件
            bindModalEvents();
        });
        
        modal.addEventListener('hidden.bs.modal', function () {
            // 模态框隐藏时重置表单
            resetForm();
        });
    }
}

// 更新模态框导航按钮状态
function updateNavigationButtonsModal(currentStep, totalSteps) {
    const nextBtn = document.getElementById('nextBtn');
    const prevBtn = document.getElementById('prevBtn');
    const saveBtn = document.getElementById('saveTestCaseBtn');
    
    // 上一步按钮
    if (prevBtn) {
        prevBtn.style.display = currentStep > 0 ? 'inline-block' : 'none';
    }
    
    // 下一步按钮
    if (nextBtn) {
        nextBtn.style.display = currentStep < totalSteps - 1 ? 'inline-block' : 'none';
    }
    
    // 保存按钮
    if (saveBtn) {
        if (currentStep === totalSteps - 1) {
            saveBtn.style.display = 'inline-block';
            nextBtn.style.display = 'none';
        } else {
            saveBtn.style.display = 'none';
        }
    }
}



// 验证表单
function validateForm() {
    const name = document.getElementById('testCaseName').value;
    if (!name || name.trim() === '') {
        alert('请填写用例名称');
        return false;
    }
    
    // 限制用例名称长度，但允许中文
    if (name.length > 100) {
        alert('用例名称不能超过100字符');
        return false;
    }
    
    const rwType = document.getElementById('rwType').value;
    const blockSize = document.getElementById('blockSize').value;
    const fileSize = document.getElementById('fileSize').value;
    const numjobs = document.getElementById('numjobs').value;
    const runtime = document.getElementById('runtime').value;
    const ioengine = document.getElementById('ioengine').value;
    
    if (!rwType) {
        alert('请选择读写类型');
        return false;
    }
    if (!blockSize) {
        alert('请填写块大小');
        return false;
    }
    if (!fileSize) {
        alert('请填写文件大小');
        return false;
    }
    if (!numjobs || numjobs < 1) {
        alert('并发作业数必须大于0');
        return false;
    }
    if (!runtime || runtime < 1) {
        alert('运行时间必须大于0');
        return false;
    }
    if (!ioengine) {
        alert('请选择I/O引擎');
        return false;
    }
    
    return true;
}

// 更新预览信息
function updatePreview() {
    document.getElementById('previewName').textContent = document.getElementById('testCaseName').value || '-';
    document.getElementById('previewDesc').textContent = document.getElementById('testCaseDesc').value || '-';
    document.getElementById('previewRw').textContent = getRwTypeName(document.getElementById('rwType').value);
    document.getElementById('previewBs').textContent = document.getElementById('blockSize').value || '-';
    document.getElementById('previewSize').textContent = document.getElementById('fileSize').value || '-';
    document.getElementById('previewEngine').textContent = document.getElementById('ioengine').value || '-';
    document.getElementById('previewDirect').textContent = document.getElementById('direct').value === '1' ? '启用' : '禁用';
    document.getElementById('previewJobs').textContent = document.getElementById('numjobs').value || '-';
    document.getElementById('previewRuntime').textContent = document.getElementById('runtime').value || '-';
}

// 获取读写类型名称
function getRwTypeName(rwValue) {
    const rwTypes = {
        'read': '顺序读',
        'write': '顺序写',
        'randread': '随机读',
        'randwrite': '随机写',
        'rw': '顺序读写',
        'randrw': '随机读写'
    };
    return rwTypes[rwValue] || rwValue;
}

// 根据读写类型处理相关参数的显示/隐藏
function handleRwTypeChange() {
    const rwType = document.getElementById('rwType').value;
    const rwmixreadGroup = document.getElementById('rwmixreadGroup');
    
    // 读比例字段只在读写混合类型时显示
    if (rwType === 'rw' || rwType === 'randrw') {
        rwmixreadGroup.style.display = 'block';
    } else {
        rwmixreadGroup.style.display = 'none';
    }
}

function loadTestCases() {
    // 从API获取测试用例数据
    fetch('/api/test-cases')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            const tableBody = document.querySelector('#testCasesTable tbody');
            tableBody.innerHTML = '';

            // API返回直接的数组
            const testCases = Array.isArray(data) ? data : [];
            
            if (!testCases || testCases.length === 0) {
                const noDataRow = document.createElement('tr');
                noDataRow.innerHTML = `<td colspan="6" class="text-center">暂无测试用例数据</td>`;
                tableBody.appendChild(noDataRow);
                return; // 早期返回，不执行后续逻辑
            }
            
            testCases.forEach(testCase => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><input type="checkbox" class="testCase-checkbox" value="${testCase.id}"></td>
                    <td>${testCase.name}</td>
                    <td>${testCase.id}</td>
                    <td>${testCase.description}</td>
                    <td>${testCase.created_at ? new Date(testCase.created_at).toLocaleDateString() : 'N/A'}</td>
                    <td>
                        <button class="btn btn-sm btn-info view-btn" data-id="${testCase.id}">查看</button>
                        <button class="btn btn-sm btn-warning update-btn" data-id="${testCase.id}">编辑</button>
                        <button class="btn btn-sm btn-danger delete-btn" data-id="${testCase.id}">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
            
            // 为新添加的按钮绑定事件（使用事件委托）
            bindDynamicButtonEvents(tableBody);
        })
        .catch(error => {
            console.error('Error loading test cases:', error);
            // 如果API调用失败，显示错误信息
            const tableBody = document.querySelector('#testCasesTable tbody');
            tableBody.innerHTML = `<tr><td colspan="6" class="text-center text-danger">加载测试用例失败: ${error.message}</td></tr>`;
        });
}

// 为动态添加的按钮绑定事件
function bindDynamicButtonEvents(container) {
    // 使用事件委托绑定删除按钮事件
    container.addEventListener('click', function(e) {
        // 删除按钮
        if (e.target.classList.contains('delete-btn')) {
            const id = e.target.getAttribute('data-id');
            deleteTestCase(id);
        }
        // 编辑按钮
        else if (e.target.classList.contains('update-btn')) {
            const id = e.target.getAttribute('data-id');
            updateTestCase(id);
        }
        // 查看按钮
        else if (e.target.classList.contains('view-btn')) {
            const id = e.target.getAttribute('data-id');
            viewTestCase(id);
        }
    });
}

// 批量删除：同步表头全选与启用/禁用批量删除按钮
document.addEventListener('DOMContentLoaded', function() {
    // 全局委托：处理表头的 selectAll 点击
    document.addEventListener('click', function(e) {
        if (!e.target) return;
        if (e.target.id === 'selectAll') {
            const checked = e.target.checked;
            document.querySelectorAll('#testCasesTable tbody .testCase-checkbox').forEach(cb => { cb.checked = checked; cb.dispatchEvent(new Event('change', { bubbles: true })); });
            updateTestCasesBatchDeleteState();
        }
    });

    // 绑定批量删除按钮
    const batchBtn = document.getElementById('batchDeleteBtn');
    if (batchBtn) {
        batchBtn.addEventListener('click', function() {
            const ids = Array.from(document.querySelectorAll('#testCasesTable tbody .testCase-checkbox:checked')).map(cb => cb.value);
            if (!ids.length) { alert('请先选择要删除的测试用例'); return; }
            if (!confirm(`确认删除 ${ids.length} 个测试用例？此操作不可撤销。`)) return;
            fetch('/api/test-cases/batch-delete', {
                method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ids })
            })
            .then(async r => {
                const txt = await r.text();
                try {
                    const json = JSON.parse(txt || '{}');
                    return { statusCode: r.status, body: json };
                } catch (e) {
                    return { statusCode: r.status, body: txt };
                }
            })
            .then(resp => {
                if (resp && resp.body && (resp.body.status === 'success' || resp.body.deleted_count > 0)) {
                    alert(`已删除 ${resp.body.deleted_count || ids.length} 个测试用例`);
                    loadTestCases(); updateTestCaseStats();
                } else {
                    console.error('批量删除失败，响应：', resp);
                    alert('批量删除失败: ' + (typeof resp.body === 'string' ? resp.body : (resp.body && resp.body.error) || '未知错误'));
                }
            })
            .catch(err => { console.error('批量删除错误', err); alert('批量删除出错: '+err.message); });
        });
    }

    // 当表格内的复选框变化时，更新批量删除按钮和表头状态
    document.addEventListener('change', function(e) {
        if (!e.target) return;
        if (e.target.classList && (e.target.classList.contains('testCase-checkbox') || e.target.classList.contains('testcase-checkbox'))) {
            updateTestCasesBatchDeleteState();
            updateTestCasesSelectAllCheckbox();
        }
    });
});

function updateTestCasesBatchDeleteState() {
    const batchBtn = document.getElementById('batchDeleteBtn');
    if (!batchBtn) return;
    const any = document.querySelectorAll('#testCasesTable tbody .testCase-checkbox:checked').length > 0;
    batchBtn.disabled = !any;
    if (any) { batchBtn.classList.remove('btn-outline-danger'); batchBtn.classList.add('btn-danger'); }
    else { batchBtn.classList.remove('btn-danger'); batchBtn.classList.add('btn-outline-danger'); }
}

function updateTestCasesSelectAllCheckbox() {
    const header = document.querySelector('#testCasesTable thead #selectAll');
    if (!header) return;
    const all = Array.from(document.querySelectorAll('#testCasesTable tbody .testCase-checkbox'));
    if (!all.length) { header.checked = false; header.indeterminate = false; return; }
    const checkedCount = all.filter(cb => cb.checked).length;
    if (checkedCount === 0) { header.checked = false; header.indeterminate = false; }
    else if (checkedCount === all.length) { header.checked = true; header.indeterminate = false; }
    else { header.checked = false; header.indeterminate = true; }
}

function updateTestCaseStats() {
    // 从API获取统计信息
    fetch('/api/test-cases')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            // 如果API返回的格式是直接的数组
            const testCases = Array.isArray(data) ? data : data.test_cases || [];
            document.getElementById('totalTestCases').textContent = testCases.length || 0;
            
            // 计算最近创建的测试用例（最近7天内）
            const sevenDaysAgo = new Date();
            sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
            
            let recentlyCreatedCount = 0;
            testCases.forEach(testCase => {
                if (testCase.created_at) {
                    const createdAt = new Date(testCase.created_at);
                    if (createdAt > sevenDaysAgo) {
                        recentlyCreatedCount++;
                    }
                }
            });
            
            document.getElementById('recentlyCreated').textContent = recentlyCreatedCount;
            
            // 统计已创建任务数（通过获取任务列表并按测试用例ID分组）
            fetch('/api/tasks')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Get tasks failed: ' + response.status);
                    }
                    return response.json();
                })
                .then(taskData => {
                    const tasks = Array.isArray(taskData) ? taskData : [];
                    
                    // 统计分配给当前页面测试用例的任务数量
                    const testCaseIds = new Set(testCases.map(tc => tc.id));
                    const assignedTasks = tasks.filter(task => testCaseIds.has(task.test_case_id));
                    
                    document.getElementById('assignedTasks').textContent = assignedTasks.length;
                })
                .catch(taskError => {
                    console.error('Error fetching tasks for stats:', taskError);
                    document.getElementById('assignedTasks').textContent = '0';
                });
        })
        .catch(error => {
            console.error('Error updating stats:', error);
            // 即使出现错误也不显示"Error"，而是使用0
            document.getElementById('totalTestCases').textContent = '0';
            document.getElementById('recentlyCreated').textContent = '0';
            document.getElementById('assignedTasks').textContent = '0';
        });
}

// 生成FIO配置
function generateFioConfig() {
    const config = {};
    
    // 基本配置参数
    const name = document.getElementById('fioName').value || document.getElementById('testCaseName').value.replace(/[^a-zA-Z0-9_]/g, '_') || 'default_test';
    if (name) config.name = name;
    
    const rw = document.getElementById('rwType').value;
    if (rw) config.rw = rw;
    
    // 如果是混合读写类型，添加读比例
    if ((rw === 'rw' || rw === 'randrw') && document.getElementById('rwmixreadGroup').style.display !== 'none') {
        const rwmixread = document.getElementById('rwmixread').value;
        if (rwmixread) {
            config.rwmixread = parseInt(rwmixread);
        }
    }
    
    // 添加其他基本配置参数
    const blockSize = document.getElementById('blockSize').value;
    if (blockSize) config.bs = blockSize;
    
    const fileSize = document.getElementById('fileSize').value;
    if (fileSize) config.size = fileSize;
    
    const numjobs = document.getElementById('numjobs').value;
    if (numjobs) config.numjobs = parseInt(numjobs);
    
    const runtime = document.getElementById('runtime').value;
    if (runtime) config.runtime = parseInt(runtime);
    
    const iodepth = document.getElementById('iodepth').value;
    if (iodepth) config.iodepth = parseInt(iodepth);
    
    // 高级配置参数
    const ioengine = document.getElementById('ioengine').value;
    if (ioengine) config.ioengine = ioengine;
    
    const direct = document.getElementById('direct').value;
    config.direct = parseInt(direct);
    
    const timeBased = document.getElementById('time_based').value;
    config.time_based = parseInt(timeBased);
    
    const verify = document.getElementById('verify').value;
    if (verify) config.verify = verify;
    
    const endFsync = document.getElementById('end_fsync').value;
    config.end_fsync = parseInt(endFsync);
    
    const filename = document.getElementById('filename').value;
    if (filename) config.filename = filename;
    
    return config;
}

// 预览FIO配置
function previewFioConfig() {
    const config = generateFioConfig();
    
    // 显示预览模态框
    const previewModal = new bootstrap.Modal(document.getElementById('configPreviewModal'));
    document.getElementById('configPreviewContent').textContent = JSON.stringify(config, null, 2);
    previewModal.show();
}

// 绑定模态框事件
function bindModalEvents() {
    // 读写类型选择变化事件
    const rwTypeSelect = document.getElementById('rwType');
    if (rwTypeSelect) {
        rwTypeSelect.addEventListener('change', handleRwTypeChange);
        // 初始化时处理默认值
        handleRwTypeChange();
    }
}

// 重置表单
function resetForm() {
    // 重置表单
    const form = document.getElementById('testCaseForm');
    if (form) {
        form.reset();
    }
    
    // 重新初始化读写类型处理
    handleRwTypeChange();
}

// 保存测试用例
function saveTestCase() {
    // 首先验证表单
    if (!validateForm()) {
        return;
    }
    
    // 获取表单数据
    const testCaseName = document.getElementById('testCaseName').value;
    const testCaseDesc = document.getElementById('testCaseDesc').value;
    const fioName = document.getElementById('fioName').value || testCaseName.replace(/[^a-zA-Z0-9_]/g, '_') || 'default_test';
    
    // 生成FIO配置
    const config = generateFioConfig();
    
    // 创建测试用例对象
    const testCase = {
        name: testCaseName,
        description: testCaseDesc,
        fio_config: config
    };
    
    // 发送POST请求到API
    fetch('/api/test-cases', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(testCase)
    })
    .then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error('创建测试用例失败: ' + response.status);
        }
    })
    .then(data => {
        // 关闭模态框
        const modalElement = document.getElementById('addTestCaseModal');
        const modal = bootstrap.Modal.getInstance(modalElement);
        if (modal) {
            // 监听模态框隐藏事件，确保完全关闭
            modalElement.addEventListener('hidden.bs.modal', function () {
                // 确保完全清理模态框相关的遮罩
                document.body.classList.remove('modal-open');
                const existingBackdrop = document.querySelector('.modal-backdrop');
                if (existingBackdrop) {
                    existingBackdrop.remove();
                }
                
                // 重置表单
                document.getElementById('testCaseForm').reset();
                resetForm();
                
                // 重新加载数据
                loadTestCases();
                updateTestCaseStats();
                
                // 显示成功通知
                showNotification('测试用例创建成功！', 'success');
            }, { once: true });
            
            modal.hide();
        } else {
            // 如果无法获取模态框实例，直接执行后续操作并清理遮罩
            document.body.classList.remove('modal-open');
            const existingBackdrop = document.querySelector('.modal-backdrop');
            if (existingBackdrop) {
                existingBackdrop.remove();
            }
            
            document.getElementById('testCaseForm').reset();
            resetForm();
            loadTestCases();
            updateTestCaseStats();
            showNotification('测试用例创建成功！', 'success');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('创建测试用例时出错: ' + error.message, 'error');
    });
}

// 重置向导
function resetWizard() {
    // 重置到第一步
    const steps = document.querySelectorAll('.step');
    steps.forEach((step, index) => {
        if (index === 0) {
            step.classList.add('active');
        } else {
            step.classList.remove('active');
        }
    });
    
    // 更新步骤指示器和按钮
    updateStepIndicator(0);
    updateNavigationButtons(0, steps.length);
    updatePreview();
    
    // 重新初始化读写类型处理
    handleRwTypeChange();
}

// 初始化创建页面的向导
function initializeCreateWizard() {
    // 初始步骤为0
    let currentStep = 0;
    updateStepIndicator(currentStep);
    
    // 绑定下一步事件
    document.getElementById('nextToStep2').addEventListener('click', function() {
        if (validateCreateStep1()) {
            document.getElementById('step1').classList.remove('active');
            document.getElementById('step2').classList.add('active');
            currentStep = 1;
            updateStepIndicator(currentStep);
            updateNavigationButtons(currentStep, 4);
        }
    });
    
    document.getElementById('backToStep1').addEventListener('click', function() {
        document.getElementById('step2').classList.remove('active');
        document.getElementById('step1').classList.add('active');
        currentStep = 0;
        updateStepIndicator(currentStep);
        updateNavigationButtons(currentStep, 4);
    });
    
    document.getElementById('nextToStep3').addEventListener('click', function() {
        if (validateCreateStep2()) {
            document.getElementById('step2').classList.remove('active');
            document.getElementById('step3').classList.add('active');
            currentStep = 2;
            updateStepIndicator(currentStep);
            updateNavigationButtons(currentStep, 4);
        }
    });
    
    document.getElementById('backToStep2').addEventListener('click', function() {
        document.getElementById('step3').classList.remove('active');
        document.getElementById('step2').classList.add('active');
        currentStep = 1;
        updateStepIndicator(currentStep);
        updateNavigationButtons(currentStep, 4);
    });
    
    document.getElementById('nextToStep4').addEventListener('click', function() {
        if (validateCreateStep3()) {
            document.getElementById('step3').classList.remove('active');
            document.getElementById('step4').classList.add('active');
            currentStep = 3;
            updateStepIndicator(currentStep);
            updateNavigationButtons(currentStep, 4);
            updateCreatePreview();
        }
    });
    
    document.getElementById('backToStep3').addEventListener('click', function() {
        document.getElementById('step4').classList.remove('active');
        document.getElementById('step3').classList.add('active');
        currentStep = 2;
        updateStepIndicator(currentStep);
        updateNavigationButtons(currentStep, 4);
    });
    
    // 绑定完成创建事件
    document.getElementById('createTestCase').addEventListener('click', createNewTestCase);
    
    // 读写类型变化事件
    document.getElementById('rwType').addEventListener('change', handleCreateRwTypeChange);
    handleCreateRwTypeChange(); // 初始化
}

// 验证创建页面步骤1
function validateCreateStep1() {
    const name = document.getElementById('testCaseName').value;
    if (!name || name.trim() === '') {
        alert('请填写用例名称');
        return false;
    }
    if (name.length > 100) {
        alert('用例名称不能超过100字符');
        return false;
    }
    return true;
}

// 验证创建页面步骤2
function validateCreateStep2() {
    const blockSize = document.getElementById('blockSize').value.trim();
    const fileSize = document.getElementById('fileSize').value.trim();
    const numjobs = parseInt(document.getElementById('numjobs').value);
    const runtime = parseInt(document.getElementById('runtime').value);
    
    if (!blockSize) {
        alert('请填写块大小');
        return false;
    }
    if (!fileSize) {
        alert('请填写文件大小');
        return false;
    }
    if (isNaN(numjobs) || numjobs < 1 || numjobs > 128) {
        alert('并发作业数必须在1-128之间');
        return false;
    }
    if (isNaN(runtime) || runtime < 1) {
        alert('运行时间必须大于0秒');
        return false;
    }
    return true;
}

// 验证创建页面步骤3
function validateCreateStep3() {
    return true;
}

// 更新创建页面预览
function updateCreatePreview() {
    document.getElementById('previewName').textContent = document.getElementById('testCaseName').value || '-';
    document.getElementById('previewDesc').textContent = document.getElementById('testCaseDesc').value || '-';
    document.getElementById('previewFioName').textContent = document.getElementById('fioName').value || '-';
    
    const config = generateCreateFioConfig();
    document.getElementById('previewConfig').textContent = JSON.stringify(config, null, 2);
}

// 生成创建页面的FIO配置
function generateCreateFioConfig() {
    const config = {};
    
    // 基本配置参数
    let name = document.getElementById('fioName').value;
    // 如果没有指定FIO任务名，使用测试用例名称并转换为合规格式
    if (!name) {
        const testCaseName = document.getElementById('testCaseName').value;
        // 将测试用例名称转换为只包含字母、数字和下划线的格式
        name = testCaseName.replace(/[^a-zA-Z0-9_]/g, '_') || 'default_test';
    }
    if (name) config.name = name;
    
    const rw = document.getElementById('rwType').value;
    if (rw) config.rw = rw;
    
    // 如果是混合读写类型，添加读比例
    if ((rw === 'rw' || rw === 'randrw')) {
        const rwmixread = document.getElementById('rwmixread').value;
        if (rwmixread) {
            config.rwmixread = parseInt(rwmixread);
        }
    }
    
    // 添加其他基本配置参数
    const blockSize = document.getElementById('blockSize').value;
    if (blockSize) config.bs = blockSize;
    
    const fileSize = document.getElementById('fileSize').value;
    if (fileSize) config.size = fileSize;
    
    const numjobs = document.getElementById('numjobs').value;
    if (numjobs) config.numjobs = parseInt(numjobs);
    
    const runtime = document.getElementById('runtime').value;
    if (runtime) config.runtime = parseInt(runtime);
    
    const iodepth = document.getElementById('iodepth').value;
    if (iodepth) config.iodepth = parseInt(iodepth);
    
    // 高级配置参数
    const ioengine = document.getElementById('ioengine').value;
    if (ioengine) config.ioengine = ioengine;
    
    const direct = document.getElementById('direct').value;
    config.direct = parseInt(direct);
    
    const timeBased = document.getElementById('time_based').value;
    config.time_based = parseInt(timeBased);
    
    const verify = document.getElementById('verify').value;
    if (verify) config.verify = verify;
    
    const endFsync = document.getElementById('end_fsync').value;
    config.end_fsync = parseInt(endFsync);
    
    const filename = document.getElementById('filename').value;
    if (filename) config.filename = filename;
    
    return config;
}

// 创建新测试用例
function createNewTestCase() {
    // 验证所有步骤
    if (!validateCreateStep1() || !validateCreateStep2() || !validateCreateStep3()) {
        return;
    }

    // 获取配置
    const testCaseName = document.getElementById('testCaseName').value.trim();
    const testCaseDesc = document.getElementById('testCaseDesc').value.trim();
    const config = generateCreateFioConfig();

    // 创建测试用例对象
    const testCase = {
        name: testCaseName,
        description: testCaseDesc,
        fio_config: config
    };

    // 显示确认对话框
    const confirmMsg = `确定要创建以下测试用例吗？\n\n名称: ${testCaseName}\n描述: ${testCaseDesc}\n\n配置:\n${JSON.stringify(config, null, 2)}`;
    
    if (confirm(confirmMsg)) {
        // 发送POST请求到API
        fetch('/api/test-cases', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(testCase)
        })
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error('创建测试用例失败: ' + response.status);
            }
        })
        .then(data => {
            alert('测试用例创建成功！');
            // 重定向到测试用例列表页面
            window.location.href = '/test-cases';
        })
        .catch(error => {
            console.error('Error:', error);
            alert('创建测试用例时出错: ' + error.message);
        });
    }
}

// 处理创建页面的读写类型变化
function handleCreateRwTypeChange() {
    const rwType = document.getElementById('rwType').value;
    const rwmixreadGroup = document.getElementById('rwmixreadGroup');
    
    // 读比例字段只在读写混合类型时显示
    if (rwType === 'rw' || rwType === 'randrw') {
        rwmixreadGroup.style.display = 'block';
    } else {
        rwmixreadGroup.style.display = 'none';
    }
}

// 更新创建页面的步骤指示器
function updateStepIndicator(currentStep) {
    const indicators = document.querySelectorAll('.step-indicator .rounded-circle');
    indicators.forEach((indicator, index) => {
        if (index === currentStep) {
            indicator.className = 'rounded-circle bg-primary text-white d-flex align-items-center justify-content-center mx-auto';
            indicator.innerHTML = '<i class="fas fa-check"></i>';
        } else if (index < currentStep) {
            indicator.className = 'rounded-circle bg-success text-white d-flex align-items-center justify-content-center mx-auto';
            indicator.innerHTML = '<i class="fas fa-check"></i>';
        } else {
            indicator.className = 'rounded-circle bg-secondary text-white d-flex align-items-center justify-content-center mx-auto';
            indicator.innerHTML = (index + 1);
        }
    });
}

// 更新导航按钮状态
function updateNavigationButtons(currentStep, totalSteps) {
    const nextBtn = document.getElementById('nextBtn');
    const prevBtn = document.getElementById('prevBtn');
    const saveBtn = document.getElementById('saveTestCaseBtn');
    
    // 上一步按钮
    if (prevBtn) {
        prevBtn.style.display = currentStep > 0 ? 'inline-block' : 'none';
    }
    
    // 下一步按钮
    if (nextBtn) {
        nextBtn.style.display = currentStep < totalSteps - 1 ? 'inline-block' : 'none';
    }
    
    // 保存按钮
    if (saveBtn) {
        if (currentStep === totalSteps - 1) {
            saveBtn.style.display = 'inline-block';
            nextBtn.style.display = 'none';
        } else {
            saveBtn.style.display = 'none';
        }
    }
}

function viewTestCase(id) {
    // 从API获取测试用例详细信息
    fetch(`/api/test-cases/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(testCase => {
            // 显示测试用例详细信息在模态框中
            document.getElementById('configPreviewContent').textContent = JSON.stringify(testCase, null, 2);
            
            // 获取或创建模态框实例
            const modalElement = document.getElementById('configPreviewModal');
            let modal = bootstrap.Modal.getInstance(modalElement);
            if (!modal) {
                modal = new bootstrap.Modal(modalElement);
            }
            
            // 确保在模态框隐藏后正确清理遮罩
            const cleanup = () => {
                // 清理body类和样式
                document.body.classList.remove('modal-open');
                document.body.style.overflow = '';
                document.body.style.paddingRight = '';
                
                // 移除所有模态框backdrop
                const backdrops = document.querySelectorAll('.modal-backdrop');
                backdrops.forEach(backdrop => backdrop.remove());
            };
            
            // 只添加一次事件监听器
            const hiddenHandler = () => {
                cleanup();
                modalElement.removeEventListener('hidden.bs.modal', hiddenHandler);
            };
            modalElement.addEventListener('hidden.bs.modal', hiddenHandler);
            
            modal.show();
        })
        .catch(error => {
            console.error('Error fetching test case:', error);
            alert('查看测试用例时出错: ' + error.message);
        });
}

function updateTestCase(id) {
    // 从API获取测试用例详细信息
    fetch(`/api/test-cases/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(testCase => {
            // 填充编辑表单
            document.getElementById('editTestCaseId').value = testCase.id;
            document.getElementById('editTestCaseName').value = testCase.name || '';
            document.getElementById('editTestCaseDesc').value = testCase.description || '';
            document.getElementById('editFioName').value = testCase.fio_config?.name || '';
            
            // 填充基本参数
            document.getElementById('editRwType').value = testCase.fio_config?.rw || '';
            document.getElementById('editBlockSize').value = testCase.fio_config?.bs || '4k';
            document.getElementById('editFileSize').value = testCase.fio_config?.size || '1G';
            document.getElementById('editNumjobs').value = testCase.fio_config?.numjobs || 8;
            document.getElementById('editRuntime').value = testCase.fio_config?.runtime || 60;
            document.getElementById('editIoengine').value = testCase.fio_config?.ioengine || 'libaio';
            document.getElementById('editIodepth').value = testCase.fio_config?.iodepth || 32;
            
            // 填充高级参数
            document.getElementById('editDirect').value = testCase.fio_config?.direct ?? 1;
            document.getElementById('editTimeBased').value = testCase.fio_config?.time_based ?? 1;
            document.getElementById('editVerify').value = testCase.fio_config?.verify || '';
            document.getElementById('editEndFsync').value = testCase.fio_config?.end_fsync ?? 0;
            document.getElementById('editFilename').value = testCase.fio_config?.filename || '/tmp/fiotest';
            
            // 处理读写混合模式的读比例
            if (testCase.fio_config?.rwmixread) {
                document.getElementById('editRwmixread').value = testCase.fio_config.rwmixread;
            }
            
            // 处理读写类型变化事件
            handleEditRwTypeChange();
            
            // 显示编辑模态框
            const modal = new bootstrap.Modal(document.getElementById('editTestCaseModal'));
            modal.show();
        })
        .catch(error => {
            console.error('Error fetching test case:', error);
            alert('编辑测试用例时出错: ' + error.message);
        });
}

// 处理编辑页面读写类型变化
function handleEditRwTypeChange() {
    const rwType = document.getElementById('editRwType').value;
    const rwmixreadGroup = document.getElementById('editRwmixreadGroup');
    
    // 读比例字段只在读写混合类型时显示
    if (rwType === 'rw' || rwType === 'randrw') {
        rwmixreadGroup.style.display = 'block';
    } else {
        rwmixreadGroup.style.display = 'none';
    }
}

// 保存编辑的测试用例
function saveEditedTestCase() {
    // 获取表单数据
    const id = document.getElementById('editTestCaseId').value;
    const name = document.getElementById('editTestCaseName').value;
    const description = document.getElementById('editTestCaseDesc').value;
    const fioName = document.getElementById('editFioName').value;
    
    // 验证必填字段
    if (!name || name.trim() === '') {
        alert('请填写用例名称');
        return;
    }
    
    if (name.length > 100) {
        alert('用例名称不能超过100字符');
        return;
    }
    
    // 生成FIO配置
    const config = {};
    
    // 基本配置参数
    if (fioName) config.name = fioName;
    
    const rw = document.getElementById('editRwType').value;
    if (rw) config.rw = rw;
    
    // 如果是混合读写类型，添加读比例
    if ((rw === 'rw' || rw === 'randrw') && document.getElementById('editRwmixreadGroup').style.display !== 'none') {
        const rwmixread = document.getElementById('editRwmixread').value;
        if (rwmixread) {
            config.rwmixread = parseInt(rwmixread);
        }
    }
    
    // 添加其他基本配置参数
    const blockSize = document.getElementById('editBlockSize').value;
    if (blockSize) config.bs = blockSize;
    
    const fileSize = document.getElementById('editFileSize').value;
    if (fileSize) config.size = fileSize;
    
    const numjobs = document.getElementById('editNumjobs').value;
    if (numjobs) config.numjobs = parseInt(numjobs);
    
    const runtime = document.getElementById('editRuntime').value;
    if (runtime) config.runtime = parseInt(runtime);
    
    const iodepth = document.getElementById('editIodepth').value;
    if (iodepth) config.iodepth = parseInt(iodepth);
    
    // 高级配置参数
    const ioengine = document.getElementById('editIoengine').value;
    if (ioengine) config.ioengine = ioengine;
    
    const direct = document.getElementById('editDirect').value;
    config.direct = parseInt(direct);
    
    const timeBased = document.getElementById('editTimeBased').value;
    config.time_based = parseInt(timeBased);
    
    const verify = document.getElementById('editVerify').value;
    if (verify) config.verify = verify;
    
    const endFsync = document.getElementById('editEndFsync').value;
    config.end_fsync = parseInt(endFsync);
    
    const filename = document.getElementById('editFilename').value;
    if (filename) config.filename = filename;
    
    // 创建测试用例对象
    const testCase = {
        name: name,
        description: description,
        fio_config: config
    };
    
    // 发送PUT请求到API更新测试用例
    fetch(`/api/test-cases/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(testCase)
    })
    .then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error('更新测试用例失败: ' + response.status);
        }
    })
    .then(data => {
        // 关闭模态框
        const modalElement = document.getElementById('editTestCaseModal');
        const modal = bootstrap.Modal.getInstance(modalElement);
        if (modal) {
            // 监听模态框隐藏事件，确保完全关闭
            modalElement.addEventListener('hidden.bs.modal', function () {
                // 确保完全清理模态框相关的遮罩
                document.body.classList.remove('modal-open');
                const existingBackdrop = document.querySelector('.modal-backdrop');
                if (existingBackdrop) {
                    existingBackdrop.remove();
                }
                
                // 重新加载数据
                loadTestCases();
                updateTestCaseStats();
                
                // 显示成功通知
                showNotification('测试用例更新成功！', 'success');
            }, { once: true });
            
            modal.hide();
        } else {
            // 如果无法获取模态框实例，直接执行后续操作并清理遮罩
            document.body.classList.remove('modal-open');
            const existingBackdrop = document.querySelector('.modal-backdrop');
            if (existingBackdrop) {
                existingBackdrop.remove();
            }
            
            loadTestCases();
            updateTestCaseStats();
            showNotification('测试用例更新成功！', 'success');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('更新测试用例时出错: ' + error.message, 'error');
    });
}

function deleteTestCase(id) {
    if (confirm('确定要删除这个测试用例吗？')) {
        // 发送DELETE请求到API
        fetch(`/api/test-cases/${id}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => {
            if (response.ok) {
                // 成功删除后重新加载数据
                loadTestCases();
                updateTestCaseStats(); // 同时更新统计数据
                showNotification('测试用例删除成功！', 'success');
            } else {
                throw new Error('删除失败: ' + response.status);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('删除测试用例时出错: ' + error.message, 'error');
        });
    }
}

// 添加一个非阻塞的通知函数
function showNotification(message, type = 'info') {
    // 创建一个临时的通知元素
    const notification = document.createElement('div');
    notification.className = `alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; min-width: 300px; z-index: 9999;';
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 3000);
}